import Vue from 'vue'
import VueRouter from 'vue-router'
//一级路由页面
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import Layout from '../views/Layout.vue'
//二级路由页面
import Artilce from '../views/sub/Artilce.vue'
import Collect from '../views/sub/Collect.vue'
import Like from '../views/sub/Like.vue'
import My from '../views/sub/My.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/detail/:id',
    name: 'Detail',
    component: () => import('../views/Detail.vue')
  },

  {
    path: '/',
    name: 'Layout',
    component: () => import('../views/Layout.vue'),
    redirect: '/artilce',
    children: [
      {
        path: '/artilce',
        name: 'Artilce',
        component: () => import('../views/sub/Artilce.vue'),
      },
      {
        path: '/collect',
        name: 'Collect',
        component: () => import('../views/sub/Collect.vue'),
      },
      {
        path: '/like',
        name: 'Like',
        component: () => import('../views/sub/Like.vue'),
      },
      {
        path: '/my',
        name: 'My',
        component: () => import('../views/sub/My.vue'),
      },

    ]
  },
]


const router = new VueRouter({
  routes
})

import { getToken } from '../utils/storage.js'
let topath = ['/login', '/register']

/*路由前置守卫,当路由值发送变化时执行*/
router.beforeEach((to, from, next) => {
  let token = getToken()
  //判断是否有token
  if (token) {
    next()
  } else {
    // console.log(to.path, 1111);
    //1.如果token失效,第一次进来要访问的是rtilce,执行else
    //2.第二次进来,白名单就会判断是否是toke或者register,由于第一次
    //设置了next('/login'),所以一定执行
    if (topath.includes(to.path)) {
      //如果要求的路径里面有login或者register,则放行
      next()
    }
    else {
      //如果没有token,需要跳转到/login
      next('/login')
    }
  }

})
//解决token失效,路由跳转错误问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, resolve, reject) {
  if (resolve || reject) return originalPush.call(this, location, resolve, reject)
  return originalPush.call(this, location).catch((e) => { })
}

export default router
